//第一模块
(function () {
    GetAnalysisWindowFiterTimes('speedratechart_time', 'd', false); 
    //时间组件绑定值
    GetAnalysisWindowFiterTimes('table_time', 'd', false);
    //单选绑定事件
    $("#TimeSelectionBox input[type='radio']").click(function () {
        // showTimeBox();
        LoadSpeedRateChartData();
    });

    // showTimeBox(); 
    //获取站点
    $.get("http://192.168.9.59:18902/stationEquipment/findAllStations", function (res) {
        if (res.data && res.data.length>0) {
            let data=res.data;
            for(let a=0;a<data.length;a++){
                $("#siteList").append("<option value='"+data[a].stationCode+"'>"+data[a].stationName+"</option>");
            }
            //用站点查询传感器
            let siteVal = $("#siteList option:selected").val();
            getSensor(siteVal)
        } else {
            $("#siteList").html("<label>暂无站点!</label>");
        }
    });

//天周月切换绑定事件
$("#speedratewindow").on('click', ".timefiltercontent a", function () {
        var type = $(this).data("type");
        $(this).addClass('active').siblings().removeClass('active');
        GetAnalysisWindowFiterTimes('speedratechart_time', type, false);
        // showTimeBox();
        LoadSpeedRateChartData();
});
$('#speedratewindow #speedratechart_time').daterangepicker(null, function (start, end, label) {
        times = $("#speedratewindow #speedratechart_time").val();
        LoadSpeedRateChartData(times);
});



//选择日期触发事件
$('#speedratewindow2 #table_time').daterangepicker(null, function (start, end, label) {
        times = $("#speedratewindow2 #table_time").val();
        getTableData(times);
});
//天周月切换绑定事件
$("#speedratewindow2").on('click', ".timefiltercontent a", function () {
        var type = $(this).data("type");
        $(this).addClass('active').siblings().removeClass('active');
        GetAnalysisWindowFiterTimes('table_time', type, false);
        getTableData();
}); 

})();
//日期选择函数
function GetAnalysisWindowFiterTimes(valuetoid, type, event) {
    var ntime = new Date();
    if (type == 'd') {
        var dstart = ntime.format("MM/dd/yyyy");
        var dend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(dstart + " - " + dend);
    } else if (type == 'w') {
        var wstart = new Date(ntime.getTime() + (24 * 60 * 60 * -6 * 1000)).format("MM/dd/yyyy");
        var wend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(wstart + ' - ' + wend);
    } else if (type == 'm') {
        var mstart = new Date(ntime.getTime() + (24 * 60 * 60 * -30 * 1000)).format("MM/dd/yyyy");
        var mend = ntime.format("MM/dd/yyyy");
        $(".timeControl #" + valuetoid).val(mstart + ' - ' + mend);
    }
    eval(event);
}
//站点选中改变
function siteChange(){
    //用站点查询传感器
    let siteVal = $("#siteList option:selected").val();
    getSensor(siteVal)
}
//用站点查询传感器
function getSensor(val){
    //0 CNSS;1降雨量;2深部位移;3地下水位
    $.post("http://192.168.9.59:18902/stationEquipment/findByValues",{stationCode:val,equipmentType:212,jscj:""}, function (res) {
        if (res.data && res.data.length>0) {
            let data=res.data;
            for(let a=0;a<data.length;a++){
                $("#ChartSelect").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
                $("#TableSelect").append("<option value='"+data[a].jscj+"' equipmentType='"+data[a].equipmentType+"' stationCode='"+data[a].stationCode+"' stationName='"+data[a].stationName+"'>"+data[a].equipmentName+"</option>");
            }
        } else {
            $("#ChartSelect").html("<label>暂无站点!</label>");
            $("#TableSelect").html("<label>暂无站点!</label>");
        }
        getAllData();
    });
}
//获取chart的数据和table的数据
function getAllData(){
    LoadSpeedRateChartData()
    getTableData();
}
//图表的传感器选择改变
function chartSensorSelectChange(){
    var SelectSensorVal = $('#ChartSelect  option:selected').val();
    getChartData(SelectSensorVal)
}
//table的传感器选择改变
function tableSelectChange(){
    getTableData()
}
function datedifference(sDate1, sDate2) {    //sDate1和sDate2是2006-12-18格式 
    var dateSpan,
        tempDate,
        iDays;
        sDate1 = Date.parse(sDate1);
        sDate2 = Date.parse(sDate2);
        dateSpan = sDate2 - sDate1;
        dateSpan = Math.abs(dateSpan);
        iDays = Math.floor(dateSpan / (24 * 3600 * 1000));
        return iDays
};
function LoadSpeedRateChartData(val) {
    var selectVal = $("#ChartSelect option:selected").val();//获取选中项的值
    var times = $("#speedratewindow #speedratechart_time").val();
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
        endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";
    if (selectVal == "") {
        $("#speedratewindow #speedratechart").html("<label>传感器选择不正确，无法加载数据!</label>");
        return;
    }
    var postUrl = "http://192.168.9.59:801/apis/result/queryAlllist?startTime="+ startTime +"&endTime="+ endTime +"&uniqure_code=" + selectVal +"&sample=0";
    // var postUrl = "http://192.168.9.59:801/apis/result/queryAlllist?startTime=&endTime=&uniqure_code=01020700026&sample=0";
    var hightChartData=[];
    //请求
    $.get(postUrl, function (result) {
        if (result.msg == "success" && result.data && result.data.length>0) {
            result.data.forEach((item)=>{
                let data=item.data;let column=item.column;
                for(let a=0;a<data.length;a++){
                    let li={}
                    for(let b=0;b<column.length;b++){
                        let key =column[b];
                        li[column[b]]=data[a][b];
                    }
                    hightChartData.push(li); 
                }
            })
            // JCSJ221A030: -1.691    value(毫秒)
            // JCSJ221A040: "2021-01-06 14:47:39"    设备入库时间
            // JCSJ221A050: "01020700026"      设备唯一编码
            // JCSJ221A060: "221"   	设备类型编码
            // JCSJ221A070: "1"       传感器
            // time: "2020-12-16 11:55:00"     时间
                let Xdata=[];let TimeData=[];
                hightChartData.forEach((item)=>{
                    // Xdata.push({y:item.JCSJ221A030*1,x:item.time});
                    Xdata.push(item.JCSJ221A030*1);
                    TimeData.push(item.time);
                })
                let option= {
                        chart: {
                            type: 'line',
                            style: {fontFamily: "'Unica One', sans-serif"},
                            plotBorderColor: '#606063',
                            zoomType: 'x',
                            spacingRight: 20,
                            height: 'auto'
                        },
                        colors: ['#E5561F', '#7FBF7F', '#7F7FFF', '#FF6F10', '#8756D8', '#310F39', '#FF7F7F'],
                        title: {text: ''},
                        credits: {enabled: false},
                        exporting: {enabled: false},
                        subtitle: {text: ''},
                        tooltip: {
                                formatter: function () {
                                    return  "<br>时间:[" + this.x + "]<br>监测数据:[" + this.y + "]";
                                }
                        },
                        xAxis: {
                            categories: TimeData,
                            tickInterval:20,
                            labels: {
                                enabled: true,
                                formatter: function() {
                                    let arr = this.value.split(" ");
                                    if(arr[1]){
                                        return arr[1];
                                    }else{
                                        return this.value;
                                    }
                                }
                            }
                        },
                        yAxis: { 
                            labels: {
                                align: 'left',
                                x: 3,
                                y: 16,
                                format: '{value:.,0f}'
                            },
                            showFirstLabel: false
                        },
                        plotOptions: {
                            series: {
                                label: {
                                    connectorAllowed: false
                                },
                                // pointStart: 2010
                            }
                        },
                        series: [{
                            name: '沉降仪监测数据（毫秒）',
                            data:Xdata
                        }]
                    };
                $('#speedratewindow #speedratechart').highcharts(option);
            } else {
                $("#speedratewindow #speedratechart").html("<label>未能成功加载GNSS数据!</label>");
            }
    });
    
}
function getTableData(val){
    var times;
    if(val){
        times=val;
    }else{
        times = $("#speedratewindow2 #table_time").val(); 
    }
    var selectVal = $("#TableSelect option:selected").val();//获取选中项的值
    // var times = $("#speedratewindow2 #table_time").val();
    var startTimeSplit = times.split('-')[0].replace(" ", "").split('/'),
        endTimeSplit = times.split('-')[1].replace(" ", "").split('/');
    var startTime = startTimeSplit[2] + "-" + startTimeSplit[0] + "-" + startTimeSplit[1]+" 00:00:00";
    var endTime = endTimeSplit[2] + "-" + endTimeSplit[0] + "-" + endTimeSplit[1]+" 23:59:59";

    var postUrl = "http://192.168.9.59:801/apis/result/queryAlllist?startTime="+ startTime +"&endTime="+ endTime +"&uniqure_code=" + selectVal +"&sample=0";
    // var postUrl = "http://192.168.9.59:801/apis/result/queryAlllist?startTime=&endTime=&uniqure_code=01020700026&sample=0";
    //请求
    let tableData=[];
    $.get(postUrl, function (result) {
          if (result.msg == "success" && result.data && result.data.length>0) {
            result.data.forEach((item)=>{
                let data=item.data;let column=item.column;
                for(let a=0;a<data.length;a++){
                    let li={}
                    for(let b=0;b<column.length;b++){
                        let key =column[b];
                        li[column[b]]=data[a][b];
                    }
                    tableData.push(li); 
                }
            })  
                layui.use(['table','layer','form','laydate'], function(){
                    var table = layui.table;
                    var layer=layui.layer;
                    var form=layui.form;
                    var $=layui.$;
                    var laydate = layui.laydate;
                    //初始赋值
                    table.render({
                            elem: '#idTest'
                            // ,url:'./json/AlarmInformation.json'
                            ,data: tableData
                            ,contentType: "application/x-www-form-urlencoded"
                            ,page: { //支持传入 laypage 组件的所有参数（某些参数除外，如：jump/elem） - 详见文档
                                layout: [ 'prev', 'page', 'next', 'skip','limit', 'count',] //自定义分页布局
                                //,curr: 5 //设定初始在第 5 页
                                ,limit:10 //一页显示多少条
                                ,limits:[5,10,15]//每页条数的选择项
                                ,groups: 2 //只显示 2 个连续页码
                                ,first: "首页" //不显示首页
                                ,last: "尾页" //不显示尾页
                                }
                                ,where:{ispage: true }
                                ,even:true
                                ,page: true  //是否启用分页
                                ,done:function(res, curr, count){}
                            ,cols: [[
                                ,{field:'time',width:165, title: '时间'}
                                ,{field:'JCSJ221A030',width:165, title: '监测数据'}
                                ,{field:'JCSJ221A040',width:165, title: '设备入库时间'}
                                ,{field:'JCSJ221A050', title: '设备唯一编码'}
                                ,{field:'JCSJ221A060', title: '设备类型编号'}//（如:101）
                                ,{field:'JCSJ221A070', title: '传感器'}
                                    // JCSJ221A030: -1.691    value(毫秒)
                                    // JCSJ221A040: "2021-01-06 14:47:39"    设备入库时间
                                    // JCSJ221A050: "01020700026"      设备唯一编码
                                    // JCSJ221A060: "221"   	设备类型编码
                                    // JCSJ221A070: "1"       传感器
                                    // time: "2020-12-16 11:55:00"     时间
         
                            ]]
                    });
            
                });
          } else {
                $("#tableBox").html("<label>暂无数据!</label>");
          }
    });
}